//
//  THealthyKit.m
//  AppClient
//
//  Created by Tink on 2017/5/7.
//  Copyright © 2017年 Facebook. All rights reserved.
//

#import <React/RCTLog.h>

#import "RCTHealthyKit.h"

@implementation RCTHealthyKit
{
  HKHealthStore *_healthStore;
  int _totalStep;
  double _totalDistance;
  RCTResponseSenderBlock _readStepCallback;
  RCTResponseSenderBlock _readStepCallback2;
  RCTResponseSenderBlock _readDistanceCallback;
  RCTResponseSenderBlock _readDistanceCallback2;
}

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(readHealthyKitData:(NSString *)type day:(int)day callback:(RCTResponseSenderBlock)callback)
{
  RCTLogInfo(@"OC log: read healthyKit data %@ %d", type, day);
  if([type isEqual: @"step"]) {
    if(_readStepCallback) {
      return;
    }
    _readStepCallback = callback;
    [self readStep:day];
  }
  else if([type isEqual: @"distance"]) {
    if(_readDistanceCallback) {
      return;
    }
    _readDistanceCallback = callback;
    [self readDistance:day];
  }
}
RCT_EXPORT_METHOD(exit:(NSString *)type){
  exit(0);
}
RCT_EXPORT_METHOD(initHealthyKitData:(RCTResponseSenderBlock)callback)
{
  RCTLogInfo(@"OC log: initHealthyKitData");
  if (![HKHealthStore isHealthDataAvailable]) {
    RCTLogInfo(@"OC log: 该设备不支持HealthKit");
    NSString *result = @"2";
    NSArray *params = [NSArray arrayWithObjects:result, nil];
    callback(params);
  }
  else {
    //创建healthStore对象
    _healthStore = [[HKHealthStore alloc]init];

    //设置需要获取的权限 这里仅设置了步数
    HKObjectType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
//    HKQuantityType *heightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];
//    HKQuantityType *weightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
//    HKQuantityType *temperatureType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyTemperature];
//    HKCharacteristicType *birthdayType = [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth];
//    HKCharacteristicType *sexType = [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex];
    HKQuantityType *distance = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
//    HKQuantityType *activeEnergyType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
    
//    NSSet *healthSet = [NSSet setWithObjects:stepType, heightType, weightType, temperatureType, birthdayType, sexType, distance, activeEnergyType, nil];
    NSSet *healthSet = [NSSet setWithObjects:stepType, distance, nil];

    //从健康应用中获取权限
    [_healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {
      if (success) {
        //获取步数后我们调用获取步数的方法
        RCTLogInfo(@"OC log: 获取权限成功");
        _totalStep = 0;

        NSString *result = @"1";
        NSArray *params = [NSArray arrayWithObjects:result, nil];
        callback(params);
      }
      else
      {
        RCTLogInfo(@"OC log: 获取权限失败");
        NSString *result = @"3";
        NSArray *params = [NSArray arrayWithObjects:result, nil];
        callback(params);
      }
    }];
  }
}

- (void) readStep:(int)day
{
  RCTLogInfo(@"OC log: readData1111");
  HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
  NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
  NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];
  //获取当前时间
  NSDate *now = [NSDate date];
  NSCalendar *calender = [NSCalendar currentCalendar];
  NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
  NSDateComponents *dateComponent = [calender components:unitFlags fromDate:now];
  int hour = (int)[dateComponent hour];
  int minute = (int)[dateComponent minute];
  int second = (int)[dateComponent second];
  NSDate *nowDay = [NSDate dateWithTimeIntervalSinceNow:  - (hour*3600 + minute * 60 + second) - 86400 * day];
  //时间结果与想象中不同是因为它显示的是0区
  NSLog(@"readStep今天%@",nowDay);
  NSDate *nextDay = [NSDate dateWithTimeIntervalSinceNow:  - (hour*3600 + minute * 60 + second)  + 86400 * (1 - day)];
  NSLog(@"readStep明天%@",nextDay);
  NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:nowDay endDate:nextDay options:(HKQueryOptionNone)];
  HKSampleQuery *sampleQuery = [[HKSampleQuery alloc]initWithSampleType:sampleType predicate:predicate limit:0 sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
    RCTLogInfo(@"OC log: readStep2222");
    _totalStep = 0;
    //设置一个int型变量来作为步数统计
    for (int i = 0; i < results.count; i ++) {
      //把结果转换为字符串类型
      HKQuantitySample *result = results[i];
      HKQuantity *quantity = result.quantity;
      NSMutableString *stepCount = (NSMutableString *)quantity;
      NSString *stepStr =[ NSString stringWithFormat:@"%@",stepCount];
      //获取51 count此类字符串前面的数字
      NSString *str = [stepStr componentsSeparatedByString:@" "][0];
      int stepNum = [str intValue];
      RCTLogInfo(@"OC log: 计算步数readStep %d",stepNum);
      //把一天中所有时间段中的步数加到一起
      _totalStep = _totalStep + stepNum;
    }
    RCTLogInfo(@"OC log: 今天的总步数readStep＝＝＝＝%d", _totalStep);
    NSNumber *totalStep = [NSNumber numberWithInt:_totalStep];;
    NSNumber *totalDistance = [NSNumber numberWithDouble:(ceilf(_totalDistance * 100) / 100)];
    NSArray *params = [NSArray arrayWithObjects:totalStep, totalDistance,nil];
    _readStepCallback2 = _readStepCallback;
    _readStepCallback = nil;
    _readStepCallback2(params);
  }];

  [_healthStore executeQuery:sampleQuery];
}

//获取公里数
- (void)readDistance:(int) day
{
  
  RCTLogInfo(@"OC log: readDistance1111");
  HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
  NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
  NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];
  //获取当前时间
  NSDate *now = [NSDate date];
  NSCalendar *calender = [NSCalendar currentCalendar];
  NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
  NSDateComponents *dateComponent = [calender components:unitFlags fromDate:now];
  int hour = (int)[dateComponent hour];
  int minute = (int)[dateComponent minute];
  int second = (int)[dateComponent second];
  NSDate *nowDay = [NSDate dateWithTimeIntervalSinceNow:  - (hour*3600 + minute * 60 + second) - 86400 * day];
  //时间结果与想象中不同是因为它显示的是0区
  NSLog(@"readDistance今天%@",nowDay);
  NSDate *nextDay = [NSDate dateWithTimeIntervalSinceNow:  - (hour*3600 + minute * 60 + second)  + 86400 * (1 - day)];
  NSLog(@"readDistance明天%@",nextDay);
  NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:nowDay endDate:nextDay options:(HKQueryOptionNone)];
  HKSampleQuery *sampleQuery = [[HKSampleQuery alloc]initWithSampleType:sampleType predicate:predicate limit:0 sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
    RCTLogInfo(@"OC log: readDistance2222");
    _totalDistance = 0;
    //设置一个int型变量来作为步数统计
    for(HKQuantitySample *quantitySample in results)
    {
      HKQuantity *quantity = quantitySample.quantity;
      HKUnit *distanceUnit = [HKUnit meterUnitWithMetricPrefix:HKMetricPrefixKilo];
      double usersHeight = [quantity doubleValueForUnit:distanceUnit];
      _totalDistance += usersHeight;
    }
//    _totalDistance += day;
    RCTLogInfo(@"OC log: readDistance今天的总距离readDistance＝＝＝＝%f", _totalDistance);
    NSNumber *totalDistance = [NSNumber numberWithDouble:_totalDistance];
    NSArray *params = [NSArray arrayWithObjects:totalDistance, nil];
    _readDistanceCallback2 = _readDistanceCallback;
    _readDistanceCallback = nil;
    _readDistanceCallback2(params);
  }];
  
  
  [_healthStore executeQuery:sampleQuery];
}

@end
